import pyautogui
import os
import time
from datetime import datetime
import tkinter as tk
from tkinter import messagebox
import threading

# 全局变量，用于控制截图线程的运行
is_running = False

def start_screenshots():
    global is_running
    if is_running:
        messagebox.showinfo("提示", "截图已经在进行中！")
        return
    is_running = True
    # 获取桌面路径
    desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")

    # 获取当前时间，用于文件夹命名
    current_time = datetime.now().strftime("%Y%m%d%H%M%S")
    folder_name = f"MR{current_time}"
    folder_path = os.path.join(desktop_path, folder_name)

    # 创建文件夹
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

    # 截图编号
    screenshot_count = 1

    def screenshot_loop():
        nonlocal screenshot_count
        global is_running
        try:
            while is_running:
                # 截图
                screenshot = pyautogui.screenshot()

                # 生成图片文件名
                file_name = f"MR{current_time}_{screenshot_count}.png"
                file_path = os.path.join(folder_path, file_name)

                # 保存截图
                screenshot.save(file_path)
                status_label.config(text=f"截图已保存到: {file_path}")

                # 编号加1
                screenshot_count += 1

                # 等待1秒
                time.sleep(0.5)
        except Exception as e:
            messagebox.showerror("错误", f"截图过程中出现错误: {str(e)}")
        finally:
            is_running = False
            status_label.config(text="截图已停止。")

    # 在新线程中运行截图循环，避免阻塞 GUI 线程
    threading.Thread(target=screenshot_loop).start()

def stop_screenshots():
    global is_running
    is_running = False
    status_label.config(text="截图已停止。")

# 创建主窗口
root = tk.Tk()
root.title("自动截图工具")

# 设置窗口置顶
root.attributes("-topmost", True)

# 设置窗口位置到屏幕左上角
root.geometry("+0+0")

# 创建启动按钮
start_button = tk.Button(root, text="开始截图", command=start_screenshots)
start_button.pack(pady=20)

# 创建停止按钮
stop_button = tk.Button(root, text="停止截图", command=stop_screenshots)
stop_button.pack(pady=10)

# 创建状态标签
status_label = tk.Label(root, text="等待开始...")
status_label.pack(pady=20)

# 运行主循环
root.mainloop()